import axios from 'axios'
import config from "./config"

var loadingInstance;
const service = axios.create({
  baseURL: config.baseUrl,
  timeout: 5000,
 //  headers: {
	//   //公共请求头配置，本项目请求头大多数接口是这个，所以这里可以配置一下，对于特殊接口单独配置
	//   "Content-Type": "application/x-www-form-urlencoded"
	// }
})

service.interceptors.request.use(
  config => {
    if(config.params && config.params.isLoading){
      uni.showLoading({
      	title: '加载中...'
      })
    }
	if(config.data && config.data.isLoading){
	  uni.showLoading({
	  	title: '加载中...'
	  })
	}
    const token = uni.getStorageSync('token');
    if(token){
      config.headers.token = token;
    }
	if(config.url === '/User/authSession'){
		config.headers.platform = 'MP-WEIXIN';
	}
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
		const res = response.data
		if(response.config.params && response.config.params.isLoading){
		  uni.hideLoading()
		}
		if(response.config.data){
			if(typeof(response.config.data) == "string" && response.config.data.constructor === String && Object.prototype.toString.call(response.config.data) == "[object String]"){
				const datas = JSON.parse(response.config.data)
				if(datas.isLoading){
					 uni.hideLoading()
				}
			}
		}
		
		return res;
  },
  error => {
	uni.showToast({
		title: '网络错误，请联系网站管理员进行反馈',
		icon: 'none',
		duration: 3000
	})
	console.log(error)
    return Promise.reject(error)
  }
)

export default service
